package com.itheima.HomeWork_day06;

public class BinarySearch {
    public static void main(String[] args) {
        int[] arrs = {1, 2, 3, 4, 5, 6, 7};
        int searchNum = 5;
        //二分查找
        System.out.println("二分查找:");
        int index = getBinarySearch(arrs, searchNum);
        System.out.println("您要找的元素索引为:" + index);

    }

    //二分查找
    public static int getBinarySearch(int[] arr, int num) {
        int start = 0;
        int end = arr.length - 1;

        for (int i = 0; i < arr.length; i++) {

            while (start <= end) {

                int mid = (start + end) / 2;

                //判断
                if (arr[mid] < num) {
                    start += 1;
                } else if (arr[mid] > num) {
                    end -= 1;
                } else {
                    return mid;
                }
            }

        }
        return -1;
    }
}
